package com.bobbygu.libnet.common;

import com.bobbygu.libnet.bean.DataResponse;
import com.bobbygu.libnet.exception.ServerException;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

/**
 * <b>类名称：</b> ResponseFunc <br/>
 * <b>类描述：</b> 用于处理DataResponse数据格式的数据<br/>
 * <p>
 * author: 顾博君 <br>
 * time:   2016/12/22 9:41 <br>
 * e-mail: gubojun@csii.com.cn <br>
 * </p>
 */

public class ResponseFunc<T> implements Function<DataResponse<T>, T> {
    public ResponseFunc() {
    }

    //此处逻辑根据约定报文进行修改，实现逻辑即可
    @Override
    public T apply(@NonNull DataResponse<T> httpResult) throws Exception {
        if (httpResult.getStatus() != DataResponse.STATUS_OK) {
            throw new ServerException(httpResult.getDesc());
        }
        if (httpResult.getResultMap() == null) {
            return getT(this);
        }
        return httpResult.getResultMap();
    }

    private T getT(Object o) {
        try {
            Type type = o.getClass().getGenericSuperclass();
//            if (type instanceof ParameterizedType) {
                return ((Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0]).newInstance();
//            } else {
//                throw new RuntimeException(o.getClass().getName() + "没有指定PO的类型");
//            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
        return null;
    }
}
